package net.kong.sns.rest.client.method;

import net.kong.sns.rest.client.KongApiMethod;
import net.kong.sns.rest.client.ClientException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:lanhuai@gmail.com">Ning Yubin</a>
 * @version $Id: AbstractMethodInvoke.java,v 1.3 2009/11/04 17:17:38 ningyubin Exp $
 */
public abstract class AbstractMethodInvoke implements MethodInvoke {

    private KongApiMethod method;
    private ResponseFormat responseFormat;
    private Map<String, String> params = new HashMap<String, String>();
    private String sessionKey = null;
    private String httpMethod = "POST";

    protected AbstractMethodInvoke(KongApiMethod method, ResponseFormat responseFormat, String sessionKey) {
        this.method = method;
        this.responseFormat = responseFormat;
        this.sessionKey = sessionKey;
        checkSessionKey();
    }

    protected AbstractMethodInvoke(KongApiMethod method, ResponseFormat responseFormat) {
        this.method = method;
        this.responseFormat = responseFormat;
        checkSessionKey();
    }

    public String getMethodName() {
        return method.getMethod();
    }

    public ResponseFormat getResponseFormat() {
        return responseFormat;
    }

    public Map<String, String> getParams() {
        return params;
    }

    public String getSessionKey() {
        return sessionKey;
    }

    public String getHttpMethod() {
        return httpMethod;
    }

    public String getParameter(String name) {
        return params.get(name);
    }

    public void setHttpMethod(String httpMethod) {
        this.httpMethod = httpMethod;
    }

    public KongApiMethod getMethod() {
        return method;
    }

    public void setMethod(KongApiMethod method) {
        this.method = method;
    }

    public void setResponseFormat(ResponseFormat responseFormat) {
        this.responseFormat = responseFormat;
    }

    public void setParameters(Map<String, String> params) {
        this.params = params;
    }

    public void setSessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
    }

    protected void setParameter(String name, String value) {
        params.put(name, value);
    }

    protected void checkSessionKey() {
        if (this.method.isSessionKeyRequired() && (this.sessionKey == null || this.sessionKey.trim().equals(""))) {
            throw new ClientException(String.format("The method[%s] require a SessionKey!", this.method.name()));
        }
    }
}
